package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.UserLocationDao;
import com.jbp.model.User;
import com.jbp.model.UserLocation;
import com.jbp.service.UserLocationService;
import com.jbp.service.UserService;
import com.jbp.utils.GeoHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (UserLocation)表服务实现类
 * @author cc
 * @since 2021-09-16 17:18:22
 */
@Service
public class UserLocationServiceImpl extends ServiceImpl<UserLocationDao, UserLocation> implements UserLocationService {
    @Autowired
    private UserService userService;

    @Override
    public PageUtils nearby(Map<String, Object> params, Integer userId) {
        IPage<User> page = new Query<User>().getPage(params);
        UserLocation location = getByUserId(userId);
        if (location!=null) {
            List<UserLocation> list = getBaseMapper().nearby(location.getLng(), location.getLat(), userId, page);
            if (list!=null) {
                List<User> users = list.stream().map(l -> {
                        User user = userService.getById((Integer) l.getUserId());
                        user = userService.getUserInformation(userId, user);
                        user.setLng(l.getLng());
                        user.setLat(l.getLat());
                        user.setAddress(l.getAddress());
                        return user;
                    }
                ).collect(Collectors.toList());
                page.setRecords(users);
                return new PageUtils(page);
            }
        }
        return null;
    }

    @Override
    public void add(UserLocation userLocation) {
        UserLocation one = getByUserId(userLocation.getUserId());
        String geoHash = GeoHash.encode(userLocation.getLat().doubleValue(), userLocation.getLng().doubleValue());
        userLocation.setGeohash(geoHash);
        if (one==null) {
            one = userLocation;
            getBaseMapper().saveLocation(one);
        } else {
            userLocation.setId(one.getId());
            getBaseMapper().updateLocationById(userLocation);
        }
    }

    @Override
    public UserLocation getByUserId(Integer userId) {
        QueryWrapper<UserLocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return getOne(queryWrapper);
    }
}